<template>
  <el-form :model="spu" ref="attributeListForm" label-width="100px" class="demo-dynamic" :disabled="disabled">

    <!--{{ attributeList }}-->
    <el-form-item
      v-for="(domain, index) in spu.attributeList"
      label="属性名"
      :key="index"
      :prop="'attributeList.' + index"
      :rules="rules.attribute">
      <el-input v-model.trim="domain.key"
                style="width: 10%;margin-left: 10px" ></el-input>
      <span style="margin-left: 15px">属性值：</span>
      <el-input v-for="(value, index) in domain.value.length"
                :key="index"
                v-model.trim="domain.value[index]"
                style="width: 10%;margin-right: 5px"></el-input>
      <el-button @click.prevent="addAttributeValue(index)" type="success" size="small" plain class="handlerAttribute">添加属性</el-button>
      <el-button @click.prevent="removeAttributeValue(index)" type="warning" size="small" plain class="handlerAttribute">删除属性</el-button>
      <el-button @click.prevent="removeSpecs(index)"  type="danger" plain size="small" class="handlerAttribute">删除变种</el-button>
    </el-form-item>

    <el-form-item>
      <!--<el-button type="primary" @click="submitForm('attributeListForm')">提交</el-button>-->
      <el-button  size="small" type="success" @click="addSpecs('uploadForm')">新增变种</el-button>

      <!--<el-button @click="addSpecs" type="success" plain>新增变种</el-button>-->
    </el-form-item>
  </el-form>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'attributeList',
    data() {
      let validateAttributes = (rule, value, callback) => {
/*        console.log(value.key)
        console.log(value.value)
        console.log(value.key.trim().length > 0)
        console.log(!value.value.includes(""))*/

        //value.key.trim().length > 0  属性key必须有值
        //value.value.length > 0  属性value这个数组必须不为空
        //!value.value.includes("")  属性value这个数组有值且值不为空
        if (value.key.trim().length > 0 && value.value.length > 0 && !value.value.includes("")) {
          callback();
        }
        else {
          callback(new Error('属性信息有误！'));
        }
      };
      return {
        rules: {
          attribute: [
            { validator: validateAttributes, trigger: 'blur' }
          ],
        },
      };
    },
    methods: {
      // 验证是否合法
      validate(){
        let flag = true;
        this.$refs['attributeListForm'].validate((valid) => {
          flag =  valid;
        });
        return flag;
      },
      // 提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 增加属性值
      addAttributeValue(index){
        this.attributeList[index].value.push("")
      },
      // 移除属性值
      removeAttributeValue(index){
        if (Object.keys(this.attributeList[index].value).length === 1){
          this.$notify.warning({title: '错误',message: '最少保持一个！', duration: 1500});
          return;
        }
        this.attributeList[index].value.pop()
      },
      // 移除新规格
      removeSpecs(index) {
        if (Object.keys(this.attributeList).length === 1){
          this.$notify.warning({title: '错误',message: '最少保持一个！', duration: 1500});
          return;
        }
        this.attributeList.splice(index, 1)
      },
      // 增加新规格
      addSpecs() {
        this.attributeList.push(
          { key:'', value: [''] }
        );
      },
    },
    computed: {
      ...mapGetters(['spu','disabled']),//数组写法

      attributeList:{// 实时更新vuex中的attributeList
        get(){
          return this.$store.getters.spu.attributeList
        },
        set(value){
          this.$store.commit('product/SET_ATTRIBUTE_LIST',value)
        }
      },
    },
    watch: {
      // 监听 store里面的数据
      "$store.getters.spu.attributeList": {
        deep: true,
        handler: function (newValue, oldValue) {
          let dbAttributeList = "";
          newValue.forEach(item => {
            const key = JSON.stringify(Object.values(item)[0])
            const value = JSON.stringify(Object.values(item)[1]);
            //console.log("{" + key + ":" + value + "}")
            let result = key + ":" + value + ",";
            dbAttributeList = dbAttributeList + result;
          })
          dbAttributeList = "{" + dbAttributeList.substr(0, dbAttributeList.length - 1) + "}"
          console.log("vuex中的attributeList改变了:",dbAttributeList)
          this.$store.commit('product/SET_DB_ATTRIBUTE_LIST',dbAttributeList)
        }
      }
    },
    mounted() {
    }
  }
</script>

<style scoped>
  .handlerAttribute{
    margin-left: 10px;
  }
</style>
